import 'package:chatgreat/helper/ability.dart';
import 'package:chatgreat/repo/api_server.dart';
import 'package:chatgreat/repo/model/misc.dart';
import 'package:bloc/bloc.dart';
import 'package:meta/meta.dart';

import '../helper/AppUtil.dart';

part 'free_count_event.dart';
part 'free_count_state.dart';

class FreeCountBloc extends Bloc<FreeCountEvent, FreeCountState> {
  List<FreeModelCount> counts = [];

  FreeCountBloc() : super(FreeCountInitial()) {
    // 重新加载所有的模型免费使用次数
    on<FreeCountReloadAllEvent>((event, emit) async {
      if (!Ability().isUserLogon()) {
        emit(FreeCountLoadedState(
          counts: await APIServer().freeChatCounts(),
          needSignin: event.checkSigninStatus,
        ));
        return;
      }

      counts = await APIServer().userFreeStatistics();
      emit(FreeCountLoadedState(counts: counts));
    });

    // 重新加载指定模型的免费使用次数
    on<FreeCountReloadEvent>((event, emit) async {

      final freeCount = await APIServer().userFreeChatCounts();
      AppUtil().touristLoginModel = freeCount;
      counts.clear();
      if (freeCount.isVip == 0) {
        counts.add(FreeModelCount(model: 'Chat3.5', name: 'Chat3.5', leftCount: freeCount.freeCount ?? 0, maxCount: 2));
      } else {
        counts.add(FreeModelCount(model: 'Chat4o', name: 'Chat4o', leftCount: freeCount.freeCount ?? 0, maxCount: 99999));
      }
      emit(FreeCountLoadedState(counts: counts));
    });
  }
}
